import { http } from '@amcax/base';
import axios from 'axios';
import { MessageTip } from '@app-cad/common/utils/MessageTip';

const httpV3 = axios.create({
  baseURL: http.defaults.baseURL,
  timeout: http.defaults.timeout,
  headers: { ...http.defaults.headers },
});
const handlers1 = (http.interceptors.request as any).handlers;
if (Array.isArray(handlers1)) {
  handlers1.forEach((interceptor: any) => {
    if (interceptor && interceptor.fulfilled) {
      httpV3.interceptors.request.use(
        interceptor.fulfilled,
        interceptor.rejected,
      );
    }
  });
}

const handlers2 = (http.interceptors.response as any).handlers;
if (Array.isArray(handlers2)) {
  handlers2.forEach((interceptor: any) => {
    if (interceptor && interceptor.fulfilled) {
      httpV3.interceptors.response.use(
        interceptor.fulfilled,
        interceptor.rejected,
      );
    }
  });
}

httpV3.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data && data.code !== 0) {
      MessageTip.error(`${data.msg}`);
      return Promise.reject(new Error(`${data.msg}`));
    }
    return response.data;
  },
  (error) => Promise.reject(error),
);

export { httpV3 };
